<?php

class __blogs_ajax extends Module {
	
	public function __construct () {
		parent::__construct ('blogs');
	}
	
	/**
	 * Подписывает пользователя на блог
	 * @return void
	 */
	public function subscribe () {
		$blogId = getRequest ('param0', 'int');

		$typesController = TypesController::getInstance ();
		$objectsController = ObjectsController::getInstance ();
		
		$oBlogType = $typesController->getTypeByName ('blog');
		
		if (!$oBlog = $objectsController->getObject ($oBlogType, $blogId)) {
			exit (new Array2XML ('data', array ('result' => '0')));
		}
		
		$oMemberType = $typesController->getTypeByName ('blog_member');
		$oAdminType = $typesController->getTypeByName ('blog_admin');
		$oModeratorType = $typesController->getTypeByName ('blog_moderator');
		
		$sel = new Selection;
		$sel->addType ($oMemberType);
		$sel->addType ($oAdminType);
		$sel->addType ($oModeratorType);
		$sel->addFilter ('user_id', ExplaySession::getUserId ());
		$sel->addFilter ('blog_id', $blogId);
		
		$res = $sel->getList ();
		
		if (count ($res)) {
			foreach ($res as $row) {
				$object = $objectsController->getObject ($typesController->getTypeById ($row[1]), $row[0]);
				$object->delete ();
				
				if ($row[1] == $oMemberType->getId ()) {
					$members = $oBlog->getValue ('count_members');
					$oBlog->setValue ('count_members', --$members);
					$oBlog->save ();
				}
			}
			
			$result = '-1';
		} else {
			$object = new Object ($oMemberType);
			$object->setValues (array (
				'user_id' => ExplaySession::getUserId (),
				'blog_id' => $blogId	
			));
			$object->createNew ();
			
			// Добавляем запись в лог
			$this->addJoinLog ($blogId);
			
			$members = $oBlog->getValue ('count_members');
			$oBlog->setValue ('count_members', ++$members);
			$oBlog->save ();
			
			$result = '1';
		}
		
		$this->flush((string) new Array2XML ('data', array ('result' => $result)), 'text/xml');
	}
	
	/**
	 * Добавляет комментарий к посту
	 * @return void
	 */
	public function ajax_addcomment () {
		$typesController = TypesController::getInstance ();
		$objectsController = ObjectsController::getInstance ();
		
		if (!$oType = $typesController->getTypeByName (getRequest ('param0'))) {
			$this->flush ((string) new Array2XML ('data', array ('result' => '0')), 'text/xml'); 
		}
		
		if (!blogs::validateType ($oType->getId ())) {
			$this->flush ((string) new Array2XML ('data', array ('result' => '0')), 'text/xml'); 
		}
		
		$requestObjectId = getRequest ('param1', 'int');
		
		$oCommentType = $typesController->getTypeByName ('comment');
		
		$testSel = new Selection;
		$testSel->addType ($oType);
		$testSel->addFilter ('id', (int) $requestObjectId);
		$testSel->addFilter ('draft', '0');
		
		if ($testSel->getTotalCount () == 0) {
			$this->flush ((string) new Array2XML ('data', array ('result' => '0')), 'text/xml'); 
		}
		
		$oComment = new Object ($oCommentType);
		$oComment->setValues ($this->getRequestData ('new', $oCommentType, true));
		$oComment->setValue ('owner_id', ExplaySession::getUserId ());
		$oComment->setValue ('pubdate', time ());
		$oComment->setValue ('type_id', $oType->getId ());
		$oComment->setValue ('object_id', $requestObjectId);
		
		if (count ($this->getValidateErrors ($oComment, $oCommentType)) > 0) {
			$this->flush ((string) new Array2XML ('data', array ('result' => '0')), 'text/xml'); 
		}
		
		if ($oComment->getValue ('rel_id') != 0 && !$oRelComment = $objectsController->getObject ($oCommentType, $oComment->getValue ('rel_id'))) {
			$this->flush ((string) new Array2XML ('data', array ('result' => '0')), 'text/xml'); 
		}
		
		$oComment->createNew ();
		
		$oPost = $objectsController->getObject ($oType, $requestObjectId);
		$countComments = $oPost->getValue ('count_comments');
		$oPost->setValue ('count_comments', ++$countComments);
		$oPost->save ();
		
		$this->postReplyNotification ($oPost, $oComment);
		
		if ($oComment->getValue ('rel_id') != 0) {
			$this->commentReplyNotification ($oPost, $oRelComment, $oComment);
		}
		
		$this->flush ((string) new Array2XML ('data', array ('result' => '1')), 'text/xml');
	}
	
	/**
	 * Голосование за публикацию
	 * @return void
	 */
	public function ajax_vote_post () {
		$typesController = TypesController::getInstance ();
		$objectsController = ObjectsController::getInstance ();
		
		$typeId = getRequest ('param0', 'int');
		$postId = getRequest ('param1', 'int');
		$mark = getRequest ('param2', 'int');
		
		if (!$oPostType = $typesController->getTypeById ($typeId)) {
			$this->flush ((string) new Array2XML ('data', array ('result' => '0')), 'text/xml');
		}
		
		if (!$oPost = $objectsController->getObject ($oPostType, $postId)) {
			$this->flush ((string) new Array2XML ('data', array ('result' => '0')), 'text/xml');
		}
		
		$oVoteType = $typesController->getTypeByName ('vote');
		
		$sel = new Selection;
		$sel->addType ($oVoteType);
		$sel->addFilter ('user_id', ExplaySession::getUserId ());
		$sel->addFilter ('object_id', $postId);
		$sel->addFilter ('type_id', $typeId);
		
		if ($sel->getTotalCount () > 0) {
			$this->flush ((string) new Array2XML ('data', array ('result' => '0')), 'text/xml');
		}
		
		$oVote = new Object ($oVoteType);
		$oVote->setValues (array (
			'type_id' => $typeId,
			'object_id' => $postId,
			'user_id' => ExplaySession::getUserId (),
			'mark' => $mark == 1 ? '1' : '0'
		));
		$oVote->createNew ();
		
		$rating = $oPost->getValue ('rating');
		$rating = $mark == 1 ? ++$rating : --$rating;
		$oPost->setValue ('rating', $rating);
		$oPost->save ();
		
		$this->flush ((string) new Array2XML ('data', array ('result' => '1', 'rating' => $rating)), 'text/xml');
	}
	
	/**
	 * Голосование за блог
	 * @return void
	 */
	public function ajax_vote_blog () {
		$typesController = TypesController::getInstance ();
		$objectsController = ObjectsController::getInstance ();
		
		$blogId = getRequest ('param0', 'int');
		$mark = getRequest ('param1', 'int');
		
		$oBlogType = $typesController->getTypeByName ('blog');
		$typeId = $oBlogType->getId ();
		
		if (!$oBlog = $objectsController->getObject ($oBlogType, $blogId)) {
			$this->flush ((string) new Array2XML ('data', array ('result' => '0')), 'text/xml');
		}
		
		$oVoteType = $typesController->getTypeByName ('vote');
		
		$sel = new Selection;
		$sel->addType ($oVoteType);
		$sel->addFilter ('user_id', ExplaySession::getUserId ());
		$sel->addFilter ('object_id', $blogId);
		$sel->addFilter ('type_id', $typeId);
		
		if ($sel->getTotalCount () > 0) {
			$this->flush ((string) new Array2XML ('data', array ('result' => '0')), 'text/xml');
		}
		
		$oVote = new Object ($oVoteType);
		$oVote->setValues (array (
			'type_id' => $typeId,
			'object_id' => $blogId,
			'user_id' => ExplaySession::getUserId (),
			'mark' => $mark == 1 ? '1' : '0'
		));
		$oVote->createNew ();
		
		$rating = (float) $oBlog->getValue ('rating');
		$dRating = (float) ('1.' . mt_rand (0,99));
		if ($mark == 1) {
			$rating = $rating + $dRating;
		} else {
			$rating = $rating - $dRating;
		}
		$oBlog->setValue ('rating', $rating);
		$oBlog->save ();
		
		$this->flush ((string) new Array2XML ('data', array ('result' => '1', 'rating' => $rating)), 'text/xml');
	}
	
	/**
	 * Показывает описание блога
	 * @return void
	 */
	public function ajax_blog_description () {
		$blogId = getRequest ('param0');
		
		if (!$oBlog = ObjectsController::getInstance()->getObject (TypesController::getInstance()->getTypeByName ('blog'), $blogId)) {
			$this->flush ((string) new Array2XML ('data', array ('error' => '1')), 'text/xml');
		}
		
		$this->flush ((string) new Array2XML ('data', array ('description' => $oBlog->getValue ('description'))), 'text/xml');
	}
	
	/**
	 * Показывает участников блога
	 * @return ModuleResponse
	 */
	public function ajax_load_members () {
		$typesController = TypesController::getInstance ();
		$objectsController = ObjectsController::getInstance ();
		
		$blogId = getRequest ('param0', 'int');
		
		if (!$objectsController->getObject ($typesController->getTypeByName ('blog'), $blogId)) {
			$this->flush ('', 'text/html');
		}
		
		$sel = new Selection;
		$sel->addType ($typesController->getTypeByName ('blog_member'));
		$sel->addType ($typesController->getTypeByName ('blog_moderator'));
		$sel->addType ($typesController->getTypeByName ('blog_admin'));
		$sel->addFilter ('blog_id', $blogId);
		
		$res = $sel->getList ();
		
		$response = new ModuleResponse;
		
		foreach ($res as $item) {
			$response->addObject ($objectsController->getObject ($typesController->getTypeById ($item[1]), $item[0]));
		}
		
		$response->setTemplate ('blogs/membersList');
		
		return $response;
	}
	
	/**
	 * @return void
	 */
	public function ajax_set_blog_member () {
		$typesController = TypesController::getInstance ();
		$objectsController = ObjectsController::getInstance ();
		
		$requestMemberType = getRequest ('param0');
		$userId = getRequest ('param1', 'int');
		$blogId = getRequest ('param2', 'int');
		
		if ($userId == ExplaySession::getUserId()) {
			$this->flush ((string) new Array2XML ('data', array ('result' => '0')), 'text/xml');
		}
		
		$oTypeMember = $typesController->getTypeByName ('blog_member');
		$oTypeAdmin = $typesController->getTypeByName ('blog_admin');
		$oTypeModerator = $typesController->getTypeByName ('blog_moderator');
		
		// Текущий пользователь должен быть администратором, чтобы модерить юзверей
		$sel = new Selection;
		$sel->addType ($oTypeAdmin);
		$sel->addFilter ('user_id', ExplaySession::getUserId ());
		$sel->addFilter ('blog_id', $blogId);
		
		if ($sel->getTotalCount () == 0) {
			$this->flush ((string) new Array2XML ('data', array ('result' => '0')), 'text/xml');
		}
		
		// Выбираем, кем является нужный пользователь в этом блоге
		$sel = new Selection;
		$sel->addType ($oTypeMember);
		$sel->addType ($oTypeAdmin);
		$sel->addType ($oTypeModerator);
		$sel->addFilter ('user_id', $userId);
		$sel->addFilter ('blog_id', $blogId);
		
		$bIsMember = false;
		$bIsAdmin = false;
		$bIsModerator = false;
		$oAdmin = false;
		$oModerator = false;
		
		$res = $sel->getList ();
		
		foreach ($res as $row) {
			if ($row[1] == $oTypeAdmin->getId ()) {
				$bIsAdmin = true;
				$oAdmin = $objectsController->getObject ($oTypeAdmin, $row[0]);
			}
			else if ($row[1] == $oTypeModerator->getId ()) {
				$bIsModerator = true;
				$oModerator = $objectsController->getObject ($oTypeModerator, $row[0]);
			}
			else {
				$bIsMember = true;
			}
		}
				
		if (!$bIsMember) {
			$this->flush ((string) new Array2XML ('data', array ('result' => '0')), 'text/xml');
		}
		
		switch ($requestMemberType) {
			case 'admin' : {
				if ($bIsModerator) { // Юзверь был модератором - снимаем
					$oModerator->delete ();
				}
				if ($bIsAdmin) { // Вай, юзверь уже админ - все ок
					$this->flush ((string) new Array2XML ('data', array ('result' => '1')), 'text/xml');
				}
				
				$object = new Object ($oTypeAdmin);
				$object->setValues (array (
					'user_id' => $userId,
					'blog_id' => $blogId
				));
				$object->createNew ();
				
				$this->flush ((string) new Array2XML ('data', array ('result' => '1')), 'text/xml');
			}
			case 'moderator' : {
				if ($bIsAdmin) {
					$oAdmin->delete ();
				}
				if ($bIsModerator) {
					$this->flush ((string) new Array2XML ('data', array ('result' => '1')), 'text/xml');
				}

				$object = new Object ($oTypeModerator);
				$object->setValues (array (
					'user_id' => $userId,
					'blog_id' => $blogId
				));
				$object->createNew ();
				
				$this->flush ((string) new Array2XML ('data', array ('result' => '1')), 'text/xml');
			}
			default : { // Снимаем админа и/или модератора
				if ($bIsModerator) {
					$oModerator->delete ();
				}
				if ($bIsAdmin) {
					$oAdmin->delete ();
				}
				$this->flush ((string) new Array2XML ('data', array ('result' => '1')), 'text/xml');
			}
		}
	}
	
	private function addJoinLog ($blogId) {
		if (Regedit::getInstance()->get ('//settings/site/use_logs') == 1) {
			$oLog = new Object (TypesController::getInstance()->getTypeByName ('log_blog_member'));
			$oLog->setValues (array (
				'date' => time (),
				'blog_id' => $blogId,
				'user_id' => ExplaySession::getUserId ()
			));
			$oLog->createNew ();
		}
	}
	
}